<template>
  <div class="card-full">
    <div class="search-box">
      <el-form ref="ruleSearchFormRef" class="search-form" :model="searchForm" inline>
        <el-form-item label="" prop="keyword">
          <el-input v-model="searchForm.keyword" placeholder="输入关键词搜索" />
        </el-form-item>
      </el-form>
      <el-button class="ml-4" type="primary" @click="getList">查询</el-button>
      <el-button plain @click="(ruleSearchFormRef.resetFields(), getList())">重置</el-button>
    </div>
    <div class="mb-2">
      <el-button v-permission="'manager:add'" type="primary" @click="isShow = true">新增</el-button>
    </div>
    <div class="table-box">
      <el-table :data="tableData" border header-align="center">
        <el-table-column prop="account" label="用户名称" min-width="120" align="center" />
        <el-table-column prop="status" label="用户头像" min-width="100" align="center">
          <template #default="scope">
            <el-image :src="scope.row.avatar || AVATAR_DEFAULT" style="width: 50px; height: 50px" />
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号码" min-width="120" align="center" />
        <el-table-column prop="email" label="邮箱" min-width="120" align="center" />
        <el-table-column prop="status" label="是否启用" min-width="100" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 1" type="primary">启用</el-tag>
            <el-tag v-else type="danger">停用</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" min-width="120" align="center">
          <template #default="scope">
            <el-button v-permission="'manager:update'" link type="primary" size="small" @click="handleClick(scope.row)"
              >编辑</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[20, 50, 80, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <el-drawer v-model="isShow" @close="resetForm">
      <template #header>
        <div class="font-bold">{{ form.id ? "编辑" : "新增" }}用户</div>
      </template>
      <template #default>
        <div>
          <el-form ref="ruleFormRef" label-position="right" label-width="auto" :model="form" :rules="rules">
            <el-form-item label="用户头像" prop="account">
              <UploadImage v-model="form.avatar" :show-file-list="false">
                <template #trigger>
                  <div class="avatar-wrapper">
                    <el-avatar :size="100" :src="form.avatar || AVATAR_DEFAULT" />
                    <div class="avatar-overlay">
                      <span>修改{{ form.avatar ? "头像" : "默认头像" }}</span>
                    </div>
                  </div>
                </template>
              </UploadImage>
            </el-form-item>
            <el-form-item label="用户名称" prop="account">
              <el-input v-model="form.account" />
            </el-form-item>
            <el-form-item
              v-if="!form.id"
              label="用户密码"
              prop="password"
              :rules="{ required: true, message: '请输入用户密码', trigger: 'blur' }"
            >
              <el-input v-model="form.password" />
            </el-form-item>
            <el-form-item label="用户角色" prop="role_ids">
              <el-select v-model="form.role_ids" placeholder="请选择用户角色" multiple>
                <el-option v-for="item in roleList" :key="item.id" :label="item.role_name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" />
            </el-form-item>
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="form.phone" />
            </el-form-item>
            <el-form-item label="是否启用" prop="status">
              <el-switch v-model="form.status" :active-value="1" :inactive-value="2" />
            </el-form-item>
          </el-form>
        </div>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="resetForm">取消</el-button>
          <el-button type="primary" @click="confirmClick(ruleFormRef)">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>
<script setup lang="ts">
import type { FormInstance, FormRules } from "element-plus";
import { ElForm, ElMessage } from "element-plus";
import { Md5 } from "ts-md5";
import * as Api from "@/api/modules/manager";
import { getRoleAll } from "@/api/modules/role";
import { AVATAR_DEFAULT } from "@/config";

const searchForm = ref({ keyword: "" });
const ruleSearchFormRef = ref<FormInstance>();
const tableData = ref([]);
const getList = async () => {
  const { data } = await Api.getList({
    ...searchForm.value,
    page: currentPage.value,
    page_size: pageSize.value
  });

  tableData.value = data.list;
  total.value = data.total;
};
const roleList = ref([]);
const getRoleList = async () => {
  const { data } = await getRoleAll();
  roleList.value = data.list;
};

const isShow = ref(false);
const form = ref<Api.ManagerData>({
  account: "",
  password: "",
  status: 1,
  role_ids: []
});
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules<Api.ManagerData>>({
  account: { required: true, message: "请输入用户名称", trigger: "blur" },
  role_ids: { required: true, message: "请选择用户角色", trigger: "blur" }
});

const confirmClick = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (form.value.id) {
        await Api.editManager(form.value).then(res => {
          getList();
          isShow.value = false;
        });
      } else {
        const data = { ...form.value, password: Md5.hashStr(form.value.password) };
        await Api.addManager(data).then(res => {
          getList();
          isShow.value = false;
        });
      }
      ElMessage({
        message: form.value.id ? "编辑成功" : "添加成功",
        type: "success"
      });
      resetForm();
    }
  });
};
const handleClick = async row => {
  const { data } = await Api.getDetail(row.id);
  form.value = data;
  isShow.value = true;
};

const resetForm = () => {
  // ruleFormRef.value?.resetFields()
  form.value = {
    account: "",
    password: "",
    status: 1,
    role_ids: []
  };
  isShow.value = false;
};

const currentPage = ref(1);
const pageSize = ref(20);
const total = ref(0);
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  getList();
};
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  getList();
};

onMounted(() => {
  getList();
  getRoleList();
});
</script>
<style lang="scss" scoped>
:deep(.el-drawer__footer) {
  padding: 15px;
  border-top: 1px solid var(--color-border-2);
}
:deep(.el-drawer__header) {
  margin-bottom: 0;
}
.avatar-wrapper {
  position: relative;
  display: inline-block;
  cursor: pointer;
}
.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100px;
  height: 100px;
  font-size: 12px;
  color: white;
  background-color: rgb(0 0 0 / 50%);
  border-radius: 50%;
  opacity: 0;
  transition: opacity 0.3s ease;
}
.avatar-wrapper:hover .avatar-overlay {
  opacity: 1;
}
</style>
